package xin.alum.aim.handler;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import io.netty.handler.logging.ByteBufFormat;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import xin.alum.aim.constant.AimAttr;

/**
 * 自定义日志输出
 */
@ChannelHandler.Sharable
public class LoggerHandler extends LoggingHandler {

    public LoggerHandler() {
        super();
    }

    public LoggerHandler(ByteBufFormat format) {
        super(format);
    }

    public LoggerHandler(LogLevel level) {
        super(level, ByteBufFormat.HEX_DUMP);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (this.logger.isEnabled(this.internalLevel)) {
            String r = String.format("READ-PF-%s-UID-%s", ctx.channel().attr(AimAttr.PLATFORM), ctx.channel().attr(AimAttr.UID));
            this.logger.log(this.internalLevel, this.format(ctx, r, msg));
        }
        super.channelRead(ctx,msg);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        if (this.logger.isEnabled(this.internalLevel)) {
            String w = String.format("WRITE-PF-%s-UID-%s", ctx.channel().attr(AimAttr.PLATFORM), ctx.channel().attr(AimAttr.UID));
            this.logger.log(this.internalLevel, this.format(ctx, w, msg));
        }
        super.write(ctx,msg,promise);
    }
}
